<template>
  <uploader
    class="styled-uploader"
    action="utils/upload-img"
    :show-upload-list="false"
    :before-upload="commonUploadCheck"
    @success="data => handleUploadSuccess(data.res.url, data.file.raw)"
  >
    <div class="uploader-container">
      <img v-if="uploaded && uploaded.data.url" :src="uploaded.data.url" />
      <template v-else>
        <el-icon><DocumentAdd /></el-icon>
        <h4>{{ text }}</h4>
      </template>
    </div>
    <template #loading>
      <div class="uploader-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <h4>上传中</h4>
      </div>
    </template>
    <template #uploaded="dataProps">
      <div class="uploader-container">
        <img v-if="showUploaded" :src="dataProps.uploadedData.url" />
        <template v-else>
          <el-icon><DocumentAdd /></el-icon>
          <h4>{{ text }}</h4>
        </template>
      </div>
    </template>
  </uploader>
</template>

<script lang="ts" setup>
import { commonUploadCheck } from '@/utils/utils'
import { DocumentAdd, Loading } from '@element-plus/icons-vue'

withDefaults(defineProps<{ text?: string; showUploaded?: boolean; uploaded?: { data: { url: string } } }>(), {
  text: '上传图片',
  showUploaded: false
})
const emit = defineEmits<{
  (e: 'success', data: { url: string; file: File })
}>()

const handleUploadSuccess = (url: string, file: File) => {
  emit('success', { url, file })
}
</script>
<style lang="scss" scoped>
.styled-uploader {
  .uploader-container {
    width: 120px;
    padding: 10px;
    color: #ffffff;
    background: #1890ff;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  }
  .uploader-container:hover {
    background: #40a9ff;
  }
  .uploader-container h4 {
    color: #ffffff;
    margin-bottom: 0;
    margin-left: 10px;
  }
  .uploader-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
